#include <my_head.h>
#include "cgic.h"
#include "project.h"

int msqid; // 消息队列id
char ID[128];

void print_html_info(char *title)
{
    printf("Content-type: text/html;charset=\"UTF-8\"\n\n"); // 固定格式 必须要加
    printf("<!DOCTYPE html>");
    printf("<html>");
    printf("<body>");
    printf("<center>");
    printf("<h1>%s</h1>", title);
    printf("<a href=\"../index.html\" target=\"blank\">点击返回登录</a> "); // 点击返回
    printf("</center>");
    printf("</body>");
    printf("</html>");
}

// 倒计时结束后回调执行函数
void sig_func(int signun)
{
    while (1){
        msgrcv(msqid, &msg, sizeof(msg_t) - sizeof(long), 1, IPC_NOWAIT);
        if (0 == strcmp(ID, msg.user.ID)){
            break;
        }else{
            msgsnd(msqid, &msg, sizeof(msg_t) - sizeof(long), 0);
        }
    }
    print_html_info("网络原因导致数据不可达，请稍后重试");
    exit(0);
}

int cgiMain(int argc, const char *argv[])
{

    // 获取消息队列的key值
    key_t my_key = ftok(MSGPATH, 'a');
    if (-1 == my_key){
        return -1;
    }
    // 获取消息队列
    int msqid = msgget(my_key, IPC_CREAT | 0666);
    if (-1 == msqid){
        return -1;
    }

    memset(&msg, 0, sizeof(msg_t));
    // 获取网页的id和密码
    cgiFormString("ID", ID, sizeof(ID));
    cgiFormString("PASSWORD", msg.user.password, sizeof(msg.user.password));

    strcpy(msg.user.ID, ID);

    // 注册信号
    signal(SIGALRM, sig_func);

    msg.msgtype = 1;
    // 发送队列消息
    msgsnd(msqid, &msg, sizeof(msg_t) - sizeof(long), 0);
    // 执行5秒倒计时
    alarm(2);
    // 阻塞接收队列消息
    msgrcv(msqid, &msg, sizeof(msg_t) - sizeof(long), 2, 0);
    
    if (1 == msg.user.flags){   
        if (1 == msg.deviceonline){
            printf("Set-Cookie:username=%s;path=/;",ID);//设置cookie
            printf("Content-type: text/html;charset=\"UTF-8\"\n\n");//固定格式 必须要加
			printf("<!DOCTYPE html>");
			printf("<html>");
			printf("<body>");
			printf("<script>window.location.href = '/Iot_select.html';</script>");//自动跳转
			printf("</body>");
			printf("</html>");
        }
        else{
            print_html_info("下位机不在线,请将下位机连接系统后重试，仍不可以联系XXXX");
        }
    }else{
        print_html_info("用户名密码错误");
    }

    return 0;
}
